import { ChatMessageType, LimitInfoType } from './types'

export const getValidChatMsg = (
  msg: ChatMessageType[],
  prompt: string,
  limitInfo: LimitInfoType
): ChatMessageType[] => {
  // 把用户设定作为对话第一条
  const systemMessage: ChatMessageType = {
    role: 'system',
    content: [
      {
        type: 'text',
        text: prompt
      }
    ]
  }

  // 只保留用户对话和模型回答
  const chatMsg = msg.filter(item => !item.ignore)

  // 1、根据短期记忆中最后轮次进行控制，
  // 2、时间控制范围内数量>=5,前端只取最后5轮，数量<=5时按时间控制
  const limitCount = limitInfo.remember_mode === 0 ? limitInfo.remember_last_num : 5

  const countLimitedMsg: ChatMessageType[] = []
  let rounds = 0
  let nextType = 'user'

  for (let i = chatMsg.length - 1; i >= 0 && rounds <= limitCount * 2; i--) {
    if (chatMsg[i].role === nextType) {
      countLimitedMsg.unshift(chatMsg[i])
      nextType = nextType === 'user' ? 'assistant' : 'user'
      rounds++
    }
  }

  if (countLimitedMsg.length > 0 && countLimitedMsg[0].role === 'assistant') {
    countLimitedMsg.shift()
  }

  // 按最后轮次控制后再按前端时间控制，暂时解决方案，后期需要后端增加消息的createTime字段
  const nowTime = Date.now()
  const limitMinute = limitInfo.remember_mode === 1 ? limitInfo.remember_last_minute : 60
  const timeLimitedMsg = countLimitedMsg.filter(item => {
    return nowTime - item.createTime <= limitMinute * 60 * 1000
  })

  if (timeLimitedMsg.length > 0 && timeLimitedMsg[0].role === 'assistant') {
    timeLimitedMsg.shift()
  }

  // 增加不合规处理，当出现一条不合规消息时过滤user和对应assistant
  const legalMgs = filterIllegalMessages(timeLimitedMsg)

  const subMsg: ChatMessageType[] = [systemMessage]
  if (chatMsg[0]?.role !== 'system') {
    subMsg.push(...legalMgs)
  } else {
    subMsg.push(...legalMgs.slice(1))
  }
  return subMsg
}

// 检查当前消息是否有 status: 30, 有的情况下过滤assistant和对应user
function filterIllegalMessages(messages) {
  const revertMessages = messages.reverse()
  const filteredMessages = []
  let skipNext = false

  for (let i = 0; i < revertMessages.length; i++) {
    const message = revertMessages[i]

    if (message.status === 30) {
      skipNext = true
      continue
    }

    if (skipNext) {
      skipNext = false
      continue
    }

    filteredMessages.push(message)
  }

  return filteredMessages.reverse()
}

export const getFileType = fileName => {
  if (!fileName) return ''
  return fileName.split('.').pop()?.toLowerCase()
}
export const getFileIconByType = type => {
  if (!type) return ''
  if (['doc', 'docx'].includes(type)) {
    return '/file_types/word.png'
  } else if (['pdf'].includes(type)) {
    return '/file_types/pdf.png'
  } else if (['ppt', 'pptx'].includes(type)) {
    return '/file_types/ppt.png'
  } else if (['wav', 'pcm', 'ogg-opus', 'speex', 'silk', 'mp3', 'm4a', 'aac', 'amr'].includes(type)) {
    return '/file_types/mp3.png'
  }else if (['txt'].includes(type)) {
    return '/file_types/txt.png' 
  } else if(['md'].includes(type)) {
    return '/file_types/md.png'
  }
}

export const getFileIconByFileName = fileName => {
  if (!fileName) return ''
  const type = getFileType(fileName)
  return getFileIconByType(type)
}

// 更新会话中定制化插件是否存在的状态
export const getSpecificPluginResultMap = toolIds => {
  const plugins = toolIds || []
  const result = {
    includedAudioPlugin: plugins.includes(20),
    // includedLenovoCloudPlugin: plugins.includes(30),
    includedLenovoCloudPlugin: true
  }
  return result
}
